<?php

namespace app\apiadmin\service\files;

use app\apiadmin\service\files\FilesService;
use app\apikanke\enums\MaterialEnum;
use app\apisell\service\posterTemplate\PosterTemplateService;
use Qcloud\Cos\Client;
use think\facade\Filesystem;

class UploadCOSService
{
    private $_cosClient;
    private $_bucketName;

    public function __construct()
    {
        $id = env("Tencent.TENCENTCLOUD_SECRET_ID");
        $key = env("Tencent.TENCENTCLOUD_SECRET_KEY");
        $region = "ap-shanghai";
        $this->_bucketName = env("Tencent.COSBucketName");
        $this->_cosClient = new Client([
            'region' => $region,
            'schema' => 'https', //协议头部，默认为http
            'credentials' => [
                'secretId' => $id,
                'secretKey' => $key,
            ],
        ]);

    }

    public function list_all_buckets()
    {
        try {
            //请求成功
            $result = $this->_cosClient->listBuckets();
            print_r($result);
        } catch (\Exception $e) {
            //请求失败
            echo ($e);
        }

    }

    public function list_all_objects($prefix_name = "uploads/", $startMarker = "", $pageSize = 8)
    {
        try {

            $query = array(
                'Bucket' => $this->_bucketName, //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
                'Delimiter' => "/", //Delimiter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object
                'EncodingType' => 'url', //编码格式，对应请求中的 encoding-type 参数
                'MaxKeys' => $pageSize, // 设置最大遍历出多少个对象, 一次listObjects最大支持1000
            );
            if (!empty($prefix_name)) {
                //Prefix表示列出的object的key以prefix开始

                $query['Prefix'] = $prefix_name;
            };
            if (!empty($startMarker)) {
                //起始对象键标记 分页使用
                $query['Marker'] = $startMarker;
            };
            $result = $this->_cosClient->listObjects($query);
            // 请求成功
            print_r($result);
        } catch (\Exception $e) {
            // 请求失败
            echo "[" . $this->_bucketName . "] list objects failed: " . $e->getMessage();
        }

    }

    public function get_download_url($key)
    {

        try {
            $bucket = $this->_bucketName; //存储桶，格式：BucketName-APPID
            $signedUrl = $this->_cosClient->getObjectUrl($bucket, $key, '+7 day');
            // 请求成功
            return $signedUrl;
        } catch (\Exception $e) {
            // 请求失败
            print_r($e);
        }

    }

    public function get_preview_url($key)
    {

        try {
            $bucket = $this->_bucketName; //存储桶，格式：BucketName-APPID
            $signedUrl = $this->_cosClient->getObjectUrlWithoutSign($bucket, $key);
            // 请求成功
            return $signedUrl;
        } catch (\Exception $e) {
            // 请求失败
            print_r($e);
        }

    }

    public function upload_file($filePath, $fileName)
    {
        try {
            $bucket = $this->_bucketName; //存储桶名称 格式：BucketName-APPID
            //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
            $file = fopen($filePath, "rb");
            if ($file) {
                $result = $this->_cosClient->putObject([
                    'Bucket' => $bucket,
                    'Key' => $fileName,
                    'Body' => $file]);
                return $this->get_preview_url($fileName);

            }
            return true;
        } catch (\Exception $e) {
            return false;
        }

    }

    public function makeSign()
    {

    }

    /**
     * @param $extension
     * @param $file
     * 本地存储
     */
    public function ProcessFile($extension, $file, $type, $by,$projectType,$uid,$source)
    {

        $fileName = Filesystem::disk('public')->putFile($extension, $file, 'uniqid');

        $sname = str_replace("\\", "/", $fileName);

        $prefix_key = "";
        switch ($type) {
            case 0:
                $prefix_key = "image";
                break;
            case 1:
                $prefix_key = "file";
                break;
            case 2:
                $prefix_key = "video";
                break;
            case 3:
                $prefix_key = "other";
                break;
        }

        $prefix = $prefix_key . '/' . date('Ymd') . "/";
        // 这里把文件上传到 COS
        $cos_uirl = $this->upload_file($file->getRealPath(), $prefix . $sname);
        Filesystem::disk('public')->delete($fileName);
        
        
        if($projectType == 'img'){
            $cos_uirl = $source == 1 ? $cos_uirl.MaterialEnum::FORMAT_COVER_IMG  :$cos_uirl;
            $data = [
                'name' => substr($sname, strripos($sname, "/") + 1),
                'f_type' => $extension,
                'type' => $type,
                'urls' => $prefix . $sname,
                'creat_time' => date('Y-m-d H:i:s', time()),
                'creat_by' => $by,
                // 'http_urls' => Request::domain() . '/storage/' . $fileName,
                'http_urls' => $cos_uirl,
                'oss' => 'COS',
                'source'=>$source,
            ];
            $result = FilesService::add($data);
        }else{
            $data = [
                'basemap' => $cos_uirl,
                'add_id' => $uid,
                'add_time' => date('Y-m-d H:i:s',time())
            ];
            $result = PosterTemplateService::created($data);
        }
        return $result;
    }

}
